<template>
  <section class="cool-switch" :style="switchStyle">
    <div class="cool-switch-body">
      <span :class="['cool-switch-input',isActive === item.value ? 'cool-switch-active' : '']" v-for="item in options" :key="item.value"
        @click="switchHandle(item)">{{ item.label }}
      </span>
      <span class="cool-switch-input-active" :style="updateActiveStyle"></span>
    </div>
  </section>
</template>

<script setup>
import { computed, onMounted, reactive, toRefs, watch } from "vue";
import { list, defProps } from "./index";

const state = reactive({
  isActive: 0,
});

const props = defineProps(defProps);

const { options, width, height } = toRefs(props);

const { isActive } = toRefs(state);

const emits = defineEmits(["update:value", "change"]);

onMounted(() => {
  if (props.options.length > 0) {
    isActive.value = props.value == null ? false : props.value;
  }
});

watch(
  () => props.value,
  (newVal) => {
    isActive.value = newVal;
  }
);

const switchHandle = (param) => {
  isActive.value = param.value;
  emits("update:value", param.value);
  emits("change", param);
};

const updateActiveStyle = computed(() => {
  let style = { width: `calc(100% / ${options.value.length})` };
  const activeIndex = options.value.findIndex(ops => ops.value === isActive.value);
  if (activeIndex !== -1) {
    style.left = `calc(100% / ${options.value.length} * ${activeIndex})`;
  }
  return style;
});

const switchStyle = computed(() => {
  let style = { width: "0px", height: "0px" };
  if (typeof width.value === 'number') {
    style.width = width.value + 'px';
  } else if (typeof width.value === 'string') {
    style.width = width.value;
  }
  if (typeof height.value === 'number') {
    style.height = height.value + 'px';
  } else if (typeof height.value === 'string') {
    style.height = height.value;
  }
  return style;
})
</script>

<style>
.cool-switch {
  width: 100%;
  max-width: 120px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  font-size: var(--font-size-12);
}
.cool-switch-body {
  width: 100%;
  height: 30px;
  padding: 1px;
  border-radius: var(--border-radius);
  border: 1px solid var(--border-color);
  background-color: var(--fill-color);
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  position: relative;
}
.cool-switch-input {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 100%;
  color: var(--font-color);
  text-align: center;
  border-radius: var(--border-radius);
  transition: all 0.3s;
  z-index: 1;
}
.cool-switch-active {
  color: #fff;
}
.cool-switch-input:hover {
  cursor: pointer;
}

.cool-switch-input-active {
  display: block;
  height: calc(100% - 2px);
  color: #fff;
  background-color: #2978ec;
  border-radius: var(--border-radius);
  position: absolute;
  transition: left 0.3s cubic-bezier(0.34, 0.69, 0.1, 1);
}
</style>
